package com.zhuhjay.service.impl;

import com.github.benmanes.caffeine.cache.Cache;
import com.zhuhjay.model.dto.ResetPwdDto;
import com.zhuhjay.model.dto.UserLoginDto;
import com.zhuhjay.model.entity.User;
import com.zhuhjay.mapper.UserMapper;
import com.zhuhjay.service.UserService;
import com.zhuhjay.util.ServletUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.zhuhjay.model.entity.table.Tables.USER;

/**
 * @author ZhuHJay
 * @date 2023/4/24 22:19
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private Cache<String, Object> loginUserCache;

    @Override
    public void login(UserLoginDto userDto) {
        User user = userMapper.selectOneByCondition(USER.NAME.eq(userDto.getName()));
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }
        if (!user.getPwd().equals(userDto.getPwd())) {
            throw new RuntimeException("密码错误");
        }
        if (user.getState() == 0) {
            throw new RuntimeException("该用户已被禁用");
        }
        String sessionId = ServletUtils.getSession().getId();
        loginUserCache.put(sessionId, user);
    }

    @Override
    public void resetPwd(ResetPwdDto resetPwdDto) {
        String sessionId = ServletUtils.getSession().getId();
        User user = (User) loginUserCache.getIfPresent(sessionId);
        if (user == null) {
            throw new RuntimeException("用户未登录");
        }
        if (!user.getPwd().equals(resetPwdDto.getPwd())) {
            throw new RuntimeException("原密码错误");
        }
        user.setPwd(resetPwdDto.getNewpwd());
        userMapper.update(user);
    }
}
